import config from '@/common/config';
import * as axios from 'axios';
import {AxiosResponse, AxiosRequestConfig} from 'axios';

const api = axios.default.create({
  baseURL: '',
  timeout: 30000,
});

api.interceptors.request.use(
  (reqConfig: AxiosRequestConfig) => reqConfig,
  (error: any) => Promise.reject(error),
);

api.interceptors.response.use(
  (response: AxiosResponse) => {
    // 判断接口请求状态
    if (response.status !== 200) {
      return Promise.reject(response);
    }
    // 判断接口返回的code  code:200=>请求成功
    if (response.data && response.data.code === 200) {
      return Promise.resolve(response.data);
    } else {
      return Promise.reject(response.data);
    }
  },
  (error: any) => Promise.reject(error),
);

function get(url: string, params?: object, baseUrl: string = 'baseUrl1'): any {
  return new Promise((resolve, reject) => {
    // 默认config.js中的第一个baseUrl1，特殊接口处理为baseUrl2
    api.defaults.baseURL = config[baseUrl];

    api.get(url, {params}).then((res: any) => {
      resolve(res.data || res.result);
    }).catch((e: any) => {
      reject(e);
    });
  });
}

export default {get};
